// Triangulator.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "Triangulator.h"
#include "algolist.manual.ru\Triangulate.h"
#include "seidel\interface.h"


namespace Alg = AlgolistManual;
using std::vector;

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
    return TRUE;
}


namespace Triangulator
{


TRIANGULATOR_API Triangles Triangulate(const Polygon& polygon)
{


#ifdef USE_ALGOLIST_ALGO


	Alg::Polygon poly;
	for (size_t i = 0; i != polygon.size(); i++)
	{
		Alg::Vertex * vertex = poly.insert(Alg::Point(polygon[i].X, polygon[i].Y));
		vertex->tag = (int)i;
	}
	Alg::List<Alg::Polygon *> * regularPolys = Alg::regularize(poly);

	Triangles result;
	for (regularPolys->first(); regularPolys->isLast(); regularPolys->next())
	{
		Alg::List<Alg::Polygon *> * triangles = Alg::triangulateMonotonePolygon(*regularPolys->val());
		for (triangles->first(); triangles->isLast(); triangles->next())
		{
			triangle triang;
			Alg::Vertex * vertices = triangles->val()->v();
			triang.V1 = (size_t)vertices[0].tag;
			triang.V2 = (size_t)vertices[1].tag;
			triang.V3 = (size_t)vertices[2].tag;
			result.push_back(triang);
		}
	}
	return result;


#else // use seidel's algorithm


	vector<double> vertices((polygon.size() + 1) * 2); // skip vertices[0] as required by interface
	vector<int> triangles(polygon.size() * 3); // i think that must be enough number of triangles
	for (size_t i = 0; i != polygon.size(); i++)
	{
		vertices[(i + 1) * 2] = polygon[i].X;
		vertices[(i + 1) * 2 + 1] = polygon[i].Y;
	}
	int npoints = (int)polygon.size();
	triangulate_polygon(1/*one contour*/, &npoints, (double (*)[2])(&vertices[0]), (int (*)[3])&triangles[0]);
	Triangles result;
	for (int i = 0; triangles[i * 3] != 0; i++)
	{
		triangle tri;
		tri.V1 = triangles[i * 3] - 1; // correction, bec vertices[0] was unused, see above
		tri.V2 = triangles[i * 3 + 1] - 1; // ...
		tri.V3 = triangles[i * 3 + 2] - 1; // ...
		result.push_back(tri);
	}
	return result;


#endif


}



} // namespace Triangulator